/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.listener;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.yami.shop.bean.bo.BrandBO;
import com.yami.shop.bean.bo.CategoryBO;
import com.yami.shop.bean.bo.ProductBO;
import com.yami.shop.bean.enums.DeliveryType;
import com.yami.shop.bean.enums.ProdStatusEnums;
import com.yami.shop.bean.enums.ShopStatus;
import com.yami.shop.bean.event.EsProductEvent;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.order.EsProductOrder;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.enums.StatusEnum;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.common.util.Arith;
import com.yami.shop.dao.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 获取es商品数据事件
 *
 * @author yami
 */
@Component("defaultEsProductListener")
@Slf4j
@AllArgsConstructor
public class EsProductListener {

    private final ProductMapper productMapper;
    private final ProdCommMapper prodCommMapper;
    private final CategoryMapper categoryMapper;
    private final ShopDetailMapper shopDetailMapper;
    private final BrandMapper brandMapper;
    private final ProdExtensionMapper prodExtensionMapper;

    @EventListener(EsProductEvent.class)
    @Order(EsProductOrder.DEFAULT)
    public void defaultEsProductListener(EsProductEvent event) {
        // 商品信息
        List<ProductBO> productList = productMapper.getProductBO(event.getProdIds());
        if (CollUtil.isEmpty(productList)) {
            return;
        }
        event.getProductList().addAll(productList);
        Set<Long> prodIds = new HashSet<>();
        Set<Long> categoryIds = new HashSet<>();
        List<Long> shopIds = new ArrayList<>();
        List<Long> brandIds = new ArrayList<>();
        for (ProductBO productBO : productList) {
            prodIds.add(productBO.getProdId());
            categoryIds.add(productBO.getCategoryId());
            categoryIds.add(productBO.getShopCategoryId());
            shopIds.add(productBO.getShopId());
            if (Objects.nonNull(productBO.getBrandId()) && productBO.getBrandId() > 0) {
                brandIds.add(productBO.getBrandId());
            }
        }
        // 商品库存
        loadProdExtension(productList, event.getProdIds());
        // 商品评论
        List<ProdComm> prodCommList = prodCommMapper.countProdCommNum(prodIds);
        Map<Long, ProdComm> prodCommMap = prodCommList.stream().collect(Collectors.toMap(ProdComm::getProdId, p -> p));
        // 商品分类信息
        List<Category> categories = categoryMapper.listAndParentByIds(categoryIds);
        Map<Long, Category> categoryMap = categories.stream().collect(Collectors.toMap(Category::getCategoryId, c -> c));
        // 商品店铺信息
        List<ShopDetail> shopDetails = shopDetailMapper.selectList(new LambdaQueryWrapper<ShopDetail>().in(ShopDetail::getShopId, shopIds));
        Map<Long, ShopDetail> shopMap = shopDetails.stream().collect(Collectors.toMap(ShopDetail::getShopId, s -> s));
        // 商品品牌信息
        Map<Long, Brand> brandMap;
        if (CollUtil.isEmpty(brandIds)) {
            brandMap = new HashMap<>(0);
        } else {
            List<Brand> brands = brandMapper.listAndLang(brandIds);
            brandMap = brands.stream().collect(Collectors.toMap(Brand::getBrandId, b -> b));
        }
        // 商品数据合并
        for (ProductBO productBO : productList) {
            try{
                productBO.setHasStock(Boolean.TRUE);
                if (Objects.isNull(productBO.getTotalStocks()) || Objects.equals(productBO.getTotalStocks(), 0)) {
                    productBO.setHasStock(Boolean.FALSE);
                }
                productBO.setAppDisplay(Boolean.TRUE);
                ProdComm prodComm = prodCommMap.get(productBO.getProdId());
                if (Objects.nonNull(prodComm)){
                    // 插入商品评论数量
                    int prodCommNum = Objects.nonNull(prodComm.getProdCommNum()) ? prodComm.getProdCommNum() : 0;
                    productBO.setCommentNum(prodCommNum);
                    // 插入商品好评率
                    int goodCommNum = Objects.nonNull(prodComm.getGoodCommNum()) ? prodComm.getGoodCommNum() : 0;
                    if (prodCommNum == 0 || goodCommNum == 0) {
                        productBO.setPositiveRating(0.0);
                    } else {
                        productBO.setPositiveRating(Arith.div(Arith.mul(goodCommNum, 100), prodCommNum, 2));
                    }
                } else {
                    productBO.setCommentNum(0);
                    productBO.setPositiveRating(0.0);
                }
                // 插入商品分类信息
                loadProdCategory(productBO, categoryMap);
                // 插入商品店铺信息
                ShopDetail shopDetail = shopMap.get(productBO.getShopId());
                if (Objects.nonNull(shopDetail)) {
                    productBO.setShopName(shopDetail.getShopName());
                    productBO.setShopType(shopDetail.getType());
                    if (productBO.getAppDisplay() && !Objects.equals(shopDetail.getShopStatus(), ShopStatus.OPEN.value())) {
                        productBO.setAppDisplay(Boolean.FALSE);
                    }
                } else if (Objects.equals(productBO.getShopId(), Constant.PLATFORM_SHOP_ID)) {
                    productBO.setShopName(Constant.PLATFORM_SHOP_NAME);
                    productBO.setShopType(1);
                } else {
                    productBO.setAppDisplay(Boolean.FALSE);
                    log.error("商品数据异常(prodId:{})-店铺(shopId:{})不存在", productBO.getProdId(), productBO.getShopId());
                }
                // 插入商品品牌信息
                if (Objects.nonNull(productBO.getBrandId()) && !Objects.equals(productBO.getBrandId(), Constant.ZERO_LONG) && brandMap.containsKey(productBO.getBrandId())) {
                    Brand brand = brandMap.get(productBO.getBrandId());
                    BrandBO brandBO = new BrandBO();
                    brandBO.setBrandId(brand.getBrandId());
                    brandBO.setBrandImg(brand.getImgUrl());
                    brandBO.setBrandNameZh(getBrandName(LanguageEnum.LANGUAGE_ZH_CN, brand.getBrandLangList()));
                    brandBO.setBrandNameEn(getBrandName(LanguageEnum.LANGUAGE_EN, brand.getBrandLangList()));
                    productBO.setBrand(brandBO);
                }
                // 商品数据处理
                loadProdData(productBO);
            } catch (Exception e) {
                log.error("商品数据异常:{}", productBO);
            }
        }
    }

    private void loadProdExtension(List<ProductBO> productList, List<Long> prodIds) {
        List<ProdExtension> prodExtensions = prodExtensionMapper.selectList(new LambdaQueryWrapper<ProdExtension>().in(ProdExtension::getProdId, prodIds));
        if (CollUtil.isEmpty(prodExtensions)) {
            return;
        }
        Map<Long, ProdExtension> prodExtensionMap = prodExtensions.stream().collect(Collectors.toMap(ProdExtension::getProdId, p -> p));
        for (ProductBO productBO : productList) {
            if (!prodExtensionMap.containsKey(productBO.getProdId())) {
                continue;
            }
            ProdExtension prodExtension = prodExtensionMap.get(productBO.getProdId());
            productBO.setTotalStocks(prodExtension.getStock());
        }

    }

    private String getBrandName(LanguageEnum languageEnum, List<BrandLang> brandLangs) {
        Map<Integer, String> langMap = brandLangs.stream().collect(Collectors.toMap(BrandLang::getLang, BrandLang::getName));
        if (langMap.containsKey(languageEnum.getLang())) {
            return langMap.get(languageEnum.getLang());
        }
        return langMap.get(Constant.DEFAULT_LANG);
    }

    private void loadProdData(ProductBO productBO) {
        // 销量统计
        if (Objects.isNull(productBO.getWaterSoldNum())) {
            productBO.setWaterSoldNum(0);
        }
        if (Objects.isNull(productBO.getActualSoldNum())) {
            productBO.setActualSoldNum(0);
        }
        productBO.setSoldNum(productBO.getActualSoldNum() + productBO.getWaterSoldNum());

        // 商品名称
        if (Objects.isNull(productBO.getProdNameZh()) && Objects.isNull(productBO.getProdNameEn()) && Objects.nonNull(productBO.getProdName())) {
            productBO.setProdNameZh(productBO.getProdName());
            productBO.setProdNameEn(productBO.getProdName());
            productBO.setBriefZh(productBO.getBrief());
            productBO.setBriefEn(productBO.getBrief());

        }
        // 配送方式
        Gson gson = new Gson();
        Product.DeliveryModeVO deliveryModeVO = gson.fromJson(productBO.getDeliveryMode(), Product.DeliveryModeVO.class);
        List<Integer> deliveries = new ArrayList<>();
        if (Objects.nonNull(deliveryModeVO.getHasCityDelivery()) && deliveryModeVO.getHasCityDelivery()) {
            // 同城配送
            deliveries.add(DeliveryType.SAME_CITY.getValue());
        }
        if (Objects.nonNull(deliveryModeVO.getHasShopDelivery()) && deliveryModeVO.getHasShopDelivery()) {
            // 店铺配送
            deliveries.add(DeliveryType.EXPRESS.getValue());
        }
        if (Objects.nonNull(deliveryModeVO.getHasUserPickUp()) && deliveryModeVO.getHasUserPickUp()) {
            // 用户自提
            deliveries.add(DeliveryType.STATION.getValue());
        }
        productBO.setDeliveries(deliveries);

        if (productBO.getAppDisplay() && !Objects.equals(productBO.getStatus(), ProdStatusEnums.NORMAL.getValue())) {
            productBO.setAppDisplay(Boolean.FALSE);
        }
        // 此字段不需要保存到es中（
        productBO.setCategoryId(null);
        productBO.setProdName(null);
        productBO.setBrief(null);
    }

    private void loadProdCategory(ProductBO productBO, Map<Long, Category> categoryMap) {
        // 平台分类信息
        Category category = categoryMap.get(productBO.getCategoryId());
        CategoryBO categoryBO = new CategoryBO();
        if (Objects.isNull(category)) {
            log.error("商品数据异常(prodId:{})-平台分类(category:{})不存在", productBO.getProdId(), productBO.getCategoryId());
            return;
        }
        categoryBO.setCategoryId(category.getCategoryId());
        categoryBO.setCategoryNameEn(category.getCategoryName());
        categoryBO.setCategoryNameEn(category.getCategoryNameEn());
        if (productBO.getAppDisplay() && !Objects.equals(category.getStatus(), StatusEnum.ENABLE.value())) {
            productBO.setAppDisplay(Boolean.FALSE);
        }
        productBO.setCategory(categoryBO);
        if (!categoryMap.containsKey(category.getParentId())) {
            return;
        }
        Category secondaryCategory = categoryMap.get(category.getParentId());
        productBO.setSecondaryCategoryId(secondaryCategory.getCategoryId());
        if (!categoryMap.containsKey(secondaryCategory.getParentId())) {
            return;
        }
        Category primaryCategory = categoryMap.get(secondaryCategory.getParentId());
        productBO.setPrimaryCategoryId(primaryCategory.getCategoryId());

    }

}
